#include "mainwindow.h"
#include "ui_mainwindow.h"
#include<QPushButton>
#include<QVBoxLayout>
#include<QGraphicsTextItem>
#include<QGraphicsProxyWidget>
#include<QGraphicsView>
#include<QString>
#include<QStyle>
#include<QDebug>
#include<QRandomGenerator>
#include<QDialog>
#include"gameconfig.h"
#include<QSettings>
#include<QMovie>
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    //初始化窗口
    setFixedSize(1500,900);
    setWindowTitle("跑酷游戏");

    //创建堆叠界面
    stackWidget = new QStackedWidget(this);
    setCentralWidget(stackWidget);

    //初始化游戏配置
    availableSkills={
        {"双段跳",":/image/tiao.jpg","允许在空中再次跳跃",3},
        {"护盾",":/image/dun.jpg","免疫一次碰撞",1},
        {"加速",":/image/su.jpg","提升移动速度5秒",2}
   } ;

    gameLevels = {
        {1,"新手关卡",30,1500},
        {2,"进阶关卡",45,1000},
        {3,"大师难度",60,800},
        {4,"无尽模式",100,1500}
    };

    //创建界面
    creatMainMenu();
    createSkillMenu();
    createLevelMenu();
    initGameScene();

    //创建启动画面
     QSize windowSize = this->size();
    splashScreen = new QWidget();
    splashScreen->setFixedSize(windowSize);
    splashLabel = new QLabel(splashScreen);
    splashLabel->setGeometry(QRect(QPoint(0,0),windowSize));
    splashLabel->setAlignment(Qt::AlignCenter);
    splashLabel->setScaledContents(true);
    splashLabel->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding);
    splashMovie = new QMovie(":/image/back.gif");
    splashLabel->setMovie(splashMovie);

    splashTimer = new QTimer(this);
    splashTimer->setSingleShot(true);
    connect(splashTimer,&QTimer::timeout,[this](){
        stackWidget->setCurrentWidget(gameView);
        startGameCore();//实际开始游戏
    });
    stackWidget->addWidget(splashScreen);
}

void MainWindow::creatMainMenu(){
    mainMenu = new QWidget();

    //设置主菜单背景
    mainMenuBgLabel = new QLabel(mainMenu);
    QPixmap bpPixmap(":/image/background.jpg");
    bpPixmap = bpPixmap.scaled(1500,900,Qt::KeepAspectRatioByExpanding);
    mainMenuBgLabel->setPixmap(bpPixmap);
    mainMenuBgLabel->setGeometry(0,0,1500,900);

    //创造半透明遮罩层
    QWidget *overlay = new QWidget(mainMenu);
    overlay->setStyleSheet("background:rgba(0,0,0,0.1);");
    overlay->setGeometry(0,0,1500,900);

    QVBoxLayout *layout = new QVBoxLayout(overlay);

    QPushButton *skillBtn = new QPushButton("选择技能");
    QPushButton *levelBtn = new QPushButton("选择关卡");
    QPushButton *startBtn = new QPushButton("开始游戏");
    QPushButton *exitBtn = new QPushButton("退出游戏");

    //样式设置
    QString btnStyle = "QPushButton{padding:15px 30px;font:bold 18px;}"
                       "QPushButton:hover{background:Qt::green}";

    skillBtn->setStyleSheet(btnStyle);
    levelBtn->setStyleSheet(btnStyle);
    startBtn->setStyleSheet(btnStyle);
    exitBtn->setStyleSheet(btnStyle+"color:red;");

    layout->addStretch();
    layout->addWidget(skillBtn,0,Qt::AlignLeft);
    layout->addWidget(levelBtn,0,Qt::AlignLeft);
    layout->addWidget(startBtn,0,Qt::AlignLeft);
    layout->addWidget(exitBtn,0,Qt::AlignLeft);
    layout->addStretch();

    connect(skillBtn,&QPushButton::clicked,this,&MainWindow::showSkillSelection);
    connect(levelBtn,&QPushButton::clicked,this,&MainWindow::showLevelSelection);
    connect(startBtn,&QPushButton::clicked,this,&MainWindow::startGame);
    connect(exitBtn,&QPushButton::clicked,qApp,&QApplication::quit);

    stackWidget->addWidget(mainMenu);

}

void MainWindow::createSkillMenu(){
    skillMenu = new QWidget();
    QGridLayout *layout = new QGridLayout(skillMenu);

    int row = 0,col = 0;
    for(const Skill &skill:availableSkills){
        QPushButton *btn = new QPushButton(skill.name);
        btn->setIcon(QIcon(skill.iconPath));
        btn->setIconSize(QSize(64,64));
        btn->setStyleSheet("padding:15px;text-align:left;");

        connect(btn,&QPushButton::clicked,[this,skill](){
            selectedSkill = skill;
            stackWidget->setCurrentWidget(mainMenu);
        });

        layout->addWidget(btn,row,col++);
        if(col>2){
            col = 0;
            row++;
        }
    }

    stackWidget->addWidget(skillMenu);
}

void MainWindow::createLevelMenu(){
    levelMenu = new QWidget();
    QVBoxLayout *layout = new QVBoxLayout(levelMenu);

    for(const Level &level:gameLevels){
        QPushButton *btn = new QPushButton(
                    QString("%1\n时间限制:%2秒").arg(level.name).arg(level.duration));
        connect(btn,&QPushButton::clicked,[this,level](){
            currentLevel = level;
            stackWidget->setCurrentWidget(mainMenu);
        });

        layout->addWidget(btn);

    }

    stackWidget->addWidget(levelMenu);

    //添加最高分显示
    QSettings settings;
    int hignScore = settings.value("endlessHignScore",0).toInt();

    QPushButton *endlessBtn = new QPushButton(QString("无尽模式\n最高纪录:%1秒").arg(hignScore));
    connect(endlessBtn,&QPushButton::clicked,[this](){
        currentLevel = gameLevels.last();
        stackWidget->setCurrentWidget(mainMenu);
    });
    layout->addWidget(endlessBtn);
}

void MainWindow::initGameScene(){
    gameView = new QGraphicsView();
    gameScene = new QGraphicsScene(this);
    gameScene->setSceneRect(0,0,1500,900);

    //添加游戏背景
    QPixmap gameBgPixmap(":/image/backg.jpg");


    if(gameBgPixmap.isNull()){
        qDebug()<<"错误：背景图片加载失败！";
        gameScene->setBackgroundBrush(Qt::darkGray);
    }
    else{
        gameBgPixmap = gameBgPixmap.scaled(gameScene->width(),gameScene->height(),Qt::KeepAspectRatioByExpanding);
        gameScene->setBackgroundBrush(gameBgPixmap);

    }
    gameView->setScene(gameScene);
    stackWidget->addWidget(gameView);

    //初始化计时器
    gameTimer = new QTimer(this);
    connect(gameTimer,&QTimer::timeout,this,&MainWindow::updateGame);

    obstacleTimer = new QTimer(this);
    connect(obstacleTimer,&QTimer::timeout,this,&MainWindow::spawnObstacle);

    countdownTimer = new QTimer(this);
    connect(countdownTimer,&QTimer::timeout,[this](){
        if(gameLevel.isEndless()) return ;//无尽模式不处理

        if(--remainingTime <= 0) gameOver(true);
        timeDisplay->setPlainText(QString("剩余时间:%1").arg(remainingTime));
    });

    coinTimer = new QTimer(this);
    connect(coinTimer,&QTimer::timeout,this,&MainWindow::spawncoin);

    m_powerUpTimer = new QTimer(this);
    connect(m_powerUpTimer,&QTimer::timeout,this,&MainWindow::spawnPowerUp);

    //初始化分数显示
    scoreDispaly = new QGraphicsTextItem();
    scoreDispaly->setPos(650,20);
    scoreDispaly->setDefaultTextColor(Qt::yellow);
    scoreDispaly->setFont(QFont("Arial",16));
    scoreDispaly->setPlainText("Score:0");
    gameScene->addItem(scoreDispaly);
}

void MainWindow::startGame(){
    if(currentLevel.id == 0||selectedSkill.name.isEmpty()) return;

    //显示启动画面
    splashLabel->setFixedSize(stackWidget->size());
    splashMovie->start();
    stackWidget->setCurrentWidget(splashScreen);

    //设置3秒后进入游戏
    splashTimer->start(2800);

    //可选：点击跳过功能
    splashLabel->installEventFilter(this);



}

void MainWindow::startGameCore(){

        //初始化游戏状态
        gameScene->clear();
        remainingTime = currentLevel.duration;
        gameRunning = true;

        //无尽模式特殊初始化
        if(gameLevel.isEndless()){
            m_elapsedTime = 0;
            m_baseObstacleInterval = gameLevel.obstacleInterval;

            //显示专属UI
            m_endlessScore = new QGraphicsTextItem();
            m_endlessScore->setPos(350,20);
            m_endlessScore->setPlainText("存活时间：0");
            gameScene->addItem(m_endlessScore);
        }

        //创建玩家
        player = new QGraphicsPixmapItem(QPixmap(":/image/player.jpg").scaled(60,80));
           player->setPos(100,750);
           gameScene->addItem(player);



        //显示UI
        timeDisplay = new QGraphicsTextItem();
        timeDisplay->setPos(600,20);
        timeDisplay->setPlainText(QString("剩余时间:%1").arg(remainingTime));
        gameScene->addItem(timeDisplay);

        skillDisplay = new QGraphicsTextItem();
        skillDisplay->setPos(20,20);
        skillDisplay->setPlainText(selectedSkill.name + "\n剩余次数:" + QString::number(selectedSkill.maxUsers));
        gameScene->addItem(skillDisplay);

        //启动计时器
        gameTimer->start(16);   //60fps
        obstacleTimer->start(currentLevel.obstacleInterval);
        countdownTimer->start(1000);
        coinTimer->start(3000);
        m_powerUpTimer->start(m_powerUpInterval);
        stackWidget->setCurrentWidget(gameView);

}
void MainWindow::keyPressEvent(QKeyEvent *event){
    if(!gameRunning)  return;

    if(event->key() == Qt::Key_Space){



        if(!isJumping||(selectedSkill.name == "双段跳"&&jumpCount < 2)){
            player->setY(player->y()-200);
            isJumping = true;
            jumpCount++;
        }
        else{ //重置跳跃状态
            isJumping = false;
            jumpCount = 0;
    }
}
    else if(event->key() == Qt::Key_S&&selectedSkill.maxUsers>0){
        useSkill();
    }
    else if(event->key() == Qt::Key_Escape){
        showPauseMenu();
    }
}


void MainWindow::useSkill(){
    if(selectedSkill.name == "护盾"){
        selectedSkill.maxUsers--;  //实现护盾逻辑
    }
    else if(selectedSkill.name == "加速"){
        selectedSkill.maxUsers--;   //实现加速逻辑
    }
    skillDisplay->setPlainText(selectedSkill.name + "\n剩余次数:" + QString::number(selectedSkill.maxUsers));
}

void MainWindow::updateGame(){
    //无尽模式计时
    if(gameLevel.isEndless()){
        m_elapsedTime++;
        m_endlessScore->setPlainText(QString("存活时间:%\n得分： %2").arg(m_elapsedTime/60));
      //动态难度：每30秒加速
        if(m_elapsedTime % 1800 == 0){
            gameLevel.obstacleInterval *= 0.9;
            obstacleTimer->setInterval(gameLevel.obstacleInterval);
        }
    }
  else{


        //重力模拟
        if(isJumping&&player->y()<750){
            player->setY(player->y()+5);
        }
        else{
            isJumping = false;
            jumpCount = 0;
        }
}

    //移动金币
    for(auto item:gameScene->items()){
        if(item->data(0).toString() == "coin"){
            item->setX(item->x() - 5);
            if(item->x()<-50){
                gameScene->removeItem(item);
                delete item;
        }
      }
    }
     QList<QGraphicsItem*>items = gameScene->items();
     foreach(QGraphicsItem *item,items){
         if(item->data(0).toString() == "obstacle"||item->data(0).toString() == "barrier"){
             item->setX(item->x() - 5);

             //移除屏幕外的障碍物
             if(item->x()<-200){
                 gameScene->removeItem(item);
                 delete item;
             }
         }
     }

}

void MainWindow::spawnObstacle(){

    QGraphicsPixmapItem *obstacle = new QGraphicsPixmapItem(QPixmap(":/image/guai.jpg").scaled(60,80));
    obstacle->setData(0,"obstacle");
    obstacle->setPos(1500,800);
    gameScene->addItem(obstacle);


    //调试输出
    qDebug()<<"生成障碍物于位置："<<obstacle->pos();
    }
//}


void MainWindow::spawnPowerUp(){
    int yPos = QRandomGenerator::global()->bounded(300,500);
    int xPos = 1500;

    powerUp = new QGraphicsPixmapItem(QPixmap(":/image/R-C.png").scaled(40,40));
    powerUp->setData(0,"powerUp");
    powerUp->setPos(xPos,yPos);
}

void MainWindow::spawncoin(){
//    //生成金币
//    QGraphicsEllipseItem *coin = new QGraphicsEllipseItem(0,0,30,30);
//    coin->setPos(800,QRandomGenerator::global()->bounded(300,500));
//    coin->setBrush(Qt::yellow);
//    coin->setData(0,"coin");
//    gameScene->addItem(coin);
}
void MainWindow::checkCollision(){

    if(player->collidingItems().count()>0){
        if(selectedSkill.name == "护盾"&&selectedSkill.maxUsers>0){
            selectedSkill.maxUsers--;
            skillDisplay->setPlainText("...");
            return;
        }
        gameOver(false);
    }

    QList<QGraphicsItem*>colliding = player->collidingItems();
    foreach(QGraphicsItem*item,colliding){
         QString type = item->data(0).toString();
        if(type== "powerUp"){
            handlePowerUpCollision();
        }

}

    if(gameLevel.isEndless()){
        gameOver(false);
        //保存最高纪录
        QSettings settings;
        if(m_elapsedTime>settings.value("endlessHignScore",0).toInt()){
               settings.setValue("endlessHignScore",m_elapsedTime);
    }
    }

}

void MainWindow::handlePowerUpCollision(){
    currengScore += 10;
    scoreDispaly->setPlainText(QString("Score:%1").arg(currengScore));
    gameScene->removeItem(powerUp);
    delete powerUp;
    powerUp = nullptr;

}
void MainWindow::handleCoinCollision(QGraphicsItem *coin){
//    score +=100;
//    scoreDispaly = new QGraphicsTextItem();
//    scoreDispaly->setPlainText(QString("Score:%1").arg(score));
//    gameOver(true);
//    gameScene->removeItem(coin);
//    delete coin;
}

void MainWindow::gameOver(bool success){
    gameRunning = false;
    gameTimer->stop();
    obstacleTimer->stop();
    countdownTimer->stop();
//    slideTimer->stop();
//    disconnect(slideTimer,0,0,0);

    QGraphicsTextItem *resultText = new QGraphicsTextItem();
    resultText->setPos(300,250);
    resultText->setHtml(QString("<h1>%1</h1>").arg(success?"通关成功!":"通关失败!"));
    gameScene->addItem(resultText);

    QPushButton *menuBtn = new QPushButton("返回主菜单");
    QString style = "QPushButton{padding:10px 20px;font:bold 18px;}"
            "QPushButton:hover{background:#E0E0E0;}";
    menuBtn->setStyleSheet(style);
    QGraphicsProxyWidget *proxy = gameScene->addWidget(menuBtn);
    proxy->setPos(350,350);
    connect(menuBtn,&QPushButton::clicked,[this](){
        stackWidget->setCurrentWidget(mainMenu);
    });
}
void MainWindow::showSkillSelection(){
    stackWidget->setCurrentWidget(skillMenu);
}

void MainWindow::showLevelSelection(){
    stackWidget->setCurrentWidget(levelMenu);
}
void MainWindow::showPauseMenu(){
    gameTimer->stop();
    QDialog pauseDialog(this);
    QVBoxLayout layout(&pauseDialog);

    QPushButton resumeBtn("继续游戏");
    QPushButton quitBtn("退出到主菜单");

    connect(&resumeBtn,&QPushButton::clicked,[&](){
        pauseDialog.accept();
        gameTimer->start();
    });

    connect(&quitBtn,&QPushButton::clicked,[&](){
        pauseDialog.accept();
        stackWidget->setCurrentWidget(mainMenu);
    });

    layout.addWidget(&resumeBtn);
    layout.addWidget(&quitBtn);
    pauseDialog.exec();
}
MainWindow::~MainWindow()
{
    delete ui;
}
